<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang>
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="mobx-state-tree,">





  <link rel="alternate" href="/blog/atom.xml" title="编程那点事" type="application/atom+xml">






<meta name="description" content="组件化的时代React、Vue、Angular等库（框架）出现后，前端进入了UI组件化开发的时代。通过合理地划分应用的功能，封装成一个个从底层到高层的组件，最后构造为一颗组件树，完成我们的应用：  App Page1 Component1 Component2 …     Page2 …  看起来真棒，不是吗？ 但是在实际开发中，还有一道绕不过去的坎：状态管理。怎么组织和划分应用的状态，UI组件如">
<meta name="keywords" content="mobx-state-tree">
<meta property="og:type" content="article">
<meta property="og:title" content="[MobX State Tree数据组件化开发][0]：开篇">
<meta property="og:url" content="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-0-：开篇/index.html">
<meta property="og:site_name" content="编程那点事">
<meta property="og:description" content="组件化的时代React、Vue、Angular等库（框架）出现后，前端进入了UI组件化开发的时代。通过合理地划分应用的功能，封装成一个个从底层到高层的组件，最后构造为一颗组件树，完成我们的应用：  App Page1 Component1 Component2 …     Page2 …  看起来真棒，不是吗？ 但是在实际开发中，还有一道绕不过去的坎：状态管理。怎么组织和划分应用的状态，UI组件如">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2019-10-07T10:19:47.552Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="[MobX State Tree数据组件化开发][0]：开篇">
<meta name="twitter:description" content="组件化的时代React、Vue、Angular等库（框架）出现后，前端进入了UI组件化开发的时代。通过合理地划分应用的功能，封装成一个个从底层到高层的组件，最后构造为一颗组件树，完成我们的应用：  App Page1 Component1 Component2 …     Page2 …  看起来真棒，不是吗？ 但是在实际开发中，还有一道绕不过去的坎：状态管理。怎么组织和划分应用的状态，UI组件如">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://lhweb.gitee.io/blog/2019/10/07/MobX-State-Tree数据组件化开发-0-：开篇/">





  <title>[MobX State Tree数据组件化开发][0]：开篇 | 编程那点事</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">编程那点事</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://lhweb.gitee.io/blog/blog/2019/10/07/MobX-State-Tree数据组件化开发-0-：开篇/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="lhweb">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="编程那点事">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">[MobX State Tree数据组件化开发][0]：开篇</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2019-10-07T16:11:57+08:00">
                2019-10-07
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="组件化的时代"><a href="#组件化的时代" class="headerlink" title="组件化的时代"></a>组件化的时代</h2><p>React、Vue、Angular等库（框架）出现后，前端进入了UI组件化开发的时代。通过合理地划分应用的功能，封装成一个个从底层到高层的组件，最后构造为一颗组件树，完成我们的应用：</p>
<ul>
<li>App<ul>
<li>Page1<ul>
<li>Component1</li>
<li>Component2</li>
<li>…</li>
</ul>
</li>
</ul>
</li>
<li>Page2</li>
<li>…</li>
</ul>
<p>看起来真棒，不是吗？</p>
<p>但是在实际开发中，还有一道绕不过去的坎：状态管理。怎么组织和划分应用的状态，UI组件如何获得自身需要的状态数据，如何复用状态部件等等，这些问题困扰了我很久。</p>
<h2 id="Flux模式"><a href="#Flux模式" class="headerlink" title="Flux模式"></a>Flux模式</h2><p>当前的状态管理方案中，以Flux模式为主流，代表性的有Redux、Vuex等。</p>
<p>举个例子，假如要实现一个电商系统，这个系统中包含“商品列表”、“收藏夹”两个功能，他们都包含一个元素结构相似的商品列表数据，但是数据的来源（接口）不同。在Redux中，需要这样写：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Reducers## </span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">productList</span> (<span class="params">state = fromJS(&#123;loading: <span class="literal">false</span>, data: []&#125;), &#123;<span class="keyword">type</span>, payload&#125;</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span> (<span class="keyword">type</span>) &#123;</span><br><span class="line">        <span class="keyword">case</span> types.PRODUCT_GET_LIST_START:</span><br><span class="line">            <span class="keyword">return</span> state.merge(&#123;loading: <span class="literal">true</span>&#125;);</span><br><span class="line">        <span class="keyword">case</span> types.PRODUCT_GET_LIST_SUCCESS:</span><br><span class="line">            <span class="keyword">return</span> state.merge(&#123;loading: <span class="literal">false</span>, data: payload&#125;);</span><br><span class="line">        <span class="keyword">case</span> types.PRODUCT_GET_LIST_FAILURE:</span><br><span class="line">            <span class="keyword">return</span> state.merge(&#123;loading: <span class="literal">false</span>&#125;);</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">return</span> state;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">favorites</span> (<span class="params">state = fromJS(&#123;loading: <span class="literal">false</span>, data: []&#125;), &#123;<span class="keyword">type</span>, payload&#125;</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">switch</span> (<span class="keyword">type</span>) &#123;</span><br><span class="line">        <span class="keyword">case</span> types.FAVORITES_GET_START:</span><br><span class="line">            <span class="keyword">return</span> state.merge(&#123;loading: <span class="literal">true</span>&#125;);</span><br><span class="line">        <span class="keyword">case</span> types.FAVORITES_GET_SUCCESS:</span><br><span class="line">            <span class="keyword">return</span> state.merge(&#123;loading: <span class="literal">false</span>, data: payload&#125;);</span><br><span class="line">        <span class="keyword">case</span> types.FAVORITES_GET_FAILURE:</span><br><span class="line">            <span class="keyword">return</span> state.merge(&#123;loading: <span class="literal">false</span>&#125;);</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">            <span class="keyword">return</span> state;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Actions</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getProducts</span> (<span class="params">params</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function">(<span class="params">dispatch, getState</span>) =&gt;</span> &#123;</span><br><span class="line">        dispatch(&#123;<span class="keyword">type</span>: types.PRODUCT_GET_LIST_START&#125;);</span><br><span class="line">        <span class="keyword">return</span> api.getProducts(params)</span><br><span class="line">            .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">                dispatch(&#123;<span class="keyword">type</span>: types.PRODUCT_GET_LIST_SUCCESS, payload: res&#125;);</span><br><span class="line">            &#125;)</span><br><span class="line">            .catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">                dispatch(&#123;<span class="keyword">type</span>: types.PRODUCT_GET_LIST_FAILURE, payload: err&#125;);</span><br><span class="line">            &#125;);</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getFavorites</span> (<span class="params">params</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function">(<span class="params">dispatch, getState</span>) =&gt;</span> &#123;</span><br><span class="line">        dispatch(&#123;<span class="keyword">type</span>: types.FAVORITES_GET_START&#125;);</span><br><span class="line">        <span class="keyword">return</span> api.getFavorites(params)</span><br><span class="line">            .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">                dispatch(&#123;<span class="keyword">type</span>: types.FAVORITES_GET_SUCCESS, payload: res&#125;);</span><br><span class="line">            &#125;)</span><br><span class="line">            .catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">                dispatch(&#123;<span class="keyword">type</span>: types.FAVORITES_GET_FAILURE, payload: err&#125;);</span><br><span class="line">            &#125;);</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> reducers = combineReducers(&#123;</span><br><span class="line">    productList,</span><br><span class="line">    favorites</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> actions = &#123;</span><br><span class="line">    getProductList,</span><br><span class="line">    getFavorites</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<p>可以看到，同样是商品列表数据的加载，需要写两份几乎相同的reducer和action。难受，非常难受！</p>
<p>看到这，有的朋友可能会说，可以封装成一个工厂方法来生成呀，比如说：</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">creteProductListReducerAndAction</span> (<span class="params">asyncTypes, service, initialState = fromJS(&#123;loading: <span class="literal">false</span>, data: []&#125;)</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> reducer = <span class="function">(<span class="params">state = initialState, &#123;<span class="keyword">type</span>, action&#125;</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">switch</span> (<span class="keyword">type</span>) &#123;</span><br><span class="line">            <span class="keyword">case</span> asyncTypes.START:</span><br><span class="line">                <span class="keyword">return</span> state.merge(&#123;loading: <span class="literal">true</span>&#125;);</span><br><span class="line">            ...</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">const</span> action = <span class="function"><span class="params">params</span> =&gt;</span> dispatch =&gt; &#123;</span><br><span class="line">        dispatch(&#123;<span class="keyword">type</span>: asyncTypes.START&#125;);</span><br><span class="line">        <span class="keyword">return</span> service(params)</span><br><span class="line">            .then(<span class="function"><span class="params">res</span> =&gt;</span> &#123;</span><br><span class="line">                dispatch(&#123;<span class="keyword">type</span>: asyncTypes.SUCCESS, payload: res&#125;);</span><br><span class="line">            &#125;)</span><br><span class="line">            .catch(<span class="function"><span class="params">err</span> =&gt;</span> &#123;</span><br><span class="line">                dispatch(&#123;<span class="keyword">type</span>: asyncTypes.FAILURE, payload: err&#125;);</span><br><span class="line">            &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> &#123;reducer, action&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>乍一看也还可以接受，但是如果有一天，我想要扩展一下favorites的reducer呢？当应用开始变得愈发丰满，需要不断地改造工厂方法才能满足业务的需求。</p>
<p>上面的例子比较简单，当然还有更好的方案，社区也有诸如dva的框架产出，但是都不够完美：复用和扩展状态部件非常困难。</p>
<h2 id="MobX-State-Tree：数据组件化"><a href="#MobX-State-Tree：数据组件化" class="headerlink" title="MobX State Tree：数据组件化"></a>MobX State Tree：数据组件化</h2><p>类似UI组件化，数据组件化很好地解决了Store模式难以复用和扩展的问题。像一个React组件，很容易在组件树的各个位置重复使用。使用HOC等手段，也能方便地对组件自身的功能进行扩展。</p>
<p>本系列文章的主角：MobX State Tree（后文中简称MST）正是实现数据组件化的利器。</p>
<blockquote>
<p>React, but for data.</p>
</blockquote>
<p>MST被称为数据管理的React，他建立在MobX的基础之上，吸收了Redux等工具的优点（state序列化、反序列化、时间旅行等，甚至能够直接替换Redux使用，见<a href="https://github.com/mobxjs/mobx-state-tree/blob/master/packages/mst-example-redux-todomvc/src/index.js#L20" target="_blank" rel="noopener">redux-todomvc example</a>）。</p>
<p>对于MST的具体细节，在开篇中就不赘述了，先来看看如何用MST来编写上文中的“商品列表”和“收藏夹”的数据容器：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; types, applySnapshot &#125; <span class="keyword">from</span> <span class="string">'mobx-state-tree'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 消息通知 BaseModel</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> Notification = types</span><br><span class="line">    .model(<span class="string">'Notification'</span>)</span><br><span class="line">    .views(<span class="function"><span class="params">self</span> =&gt;</span> (&#123;</span><br><span class="line">        <span class="keyword">get</span> notification () &#123;</span><br><span class="line">            <span class="keyword">return</span> &#123;</span><br><span class="line">                success (msg) &#123;</span><br><span class="line">                    <span class="built_in">console</span>.log(msg);</span><br><span class="line">                &#125;,</span><br><span class="line">                error (msg) &#123;</span><br><span class="line">                    <span class="built_in">console</span>.error(msg);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 可加载 BaseModel</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> Loadable = types</span><br><span class="line">    .model(<span class="string">'Loadable'</span>, &#123;</span><br><span class="line">        loading: types.optional(types.boolean, <span class="literal">false</span>)</span><br><span class="line">    &#125;)</span><br><span class="line">    .actions(<span class="function"><span class="params">self</span> =&gt;</span> (&#123;</span><br><span class="line">        setLoading (loading: boolean) &#123;</span><br><span class="line">            self.loading = loading;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 远端资源 BaseModel</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> RemoteResource = types.compose(Loadable, Notification)</span><br><span class="line">    .named(<span class="string">'RemoteResource'</span>)</span><br><span class="line">    .action(<span class="function"><span class="params">self</span> =&gt;</span> (&#123;</span><br><span class="line">        <span class="keyword">async</span> fetch (...args) &#123;</span><br><span class="line">            self.setLoading(<span class="literal">true</span>);</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">// self.serviceCall为获取数据的接口方法</span></span><br><span class="line">                <span class="comment">// 需要在扩展RemoteResource时定义在action</span></span><br><span class="line">                <span class="keyword">const</span> res = <span class="keyword">await</span> self.serviceCall(...args);</span><br><span class="line">                </span><br><span class="line">                <span class="comment">// self.data用于保存返回的数据</span></span><br><span class="line">                <span class="comment">// 需要在扩展RemoteResource时定义在props中</span></span><br><span class="line">                applySnapshot(self.data, res);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (err) &#123;</span><br><span class="line">                self.notification.error(err);</span><br><span class="line">            &#125;</span><br><span class="line">            self.setLoading(<span class="literal">false</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br><span class="line">    </span><br><span class="line"><span class="comment">// 商品Model</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> ProductItem = types.model(<span class="string">'ProductItem'</span>, &#123;</span><br><span class="line">    prodName: types.string,</span><br><span class="line">    price: types.number,</span><br><span class="line">    ...</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 商品列表数据Model</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> ProductItemList = RemoteResource</span><br><span class="line">    .named(<span class="string">'ProductItemList'</span>)</span><br><span class="line">    .props(&#123;</span><br><span class="line">        data: types.array(ProductItem),</span><br><span class="line">    &#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 商品列表Model</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> ProductList = ProductItemList</span><br><span class="line">    .named(<span class="string">'ProductList'</span>)</span><br><span class="line">    .actions(<span class="function"><span class="params">self</span> =&gt;</span> (&#123;</span><br><span class="line">        serviceCall (params) &#123;</span><br><span class="line">            <span class="keyword">return</span> apis.getProductList(params);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br><span class="line"></span><br><span class="line"><span class="comment">// 收藏夹Model</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> Favorites = ProductItemList</span><br><span class="line">    .named(<span class="string">'Favorites'</span>)</span><br><span class="line">    .actions(<span class="function"><span class="params">self</span> =&gt;</span> (&#123;</span><br><span class="line">        serviceCall (params) &#123;</span><br><span class="line">            <span class="keyword">return</span> apis.getFavorites(params);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;));</span><br></pre></td></tr></table></figure>
<p>一不小心，代码写得比Redux版本还要多了[捂脸]，但是仔细看看，上面的代码中封装了一些细粒度的组件，然后通过组合和扩展，几行代码就得到了我们想要的“商品列表”和“收藏夹”的数据容器。</p>
<p>在MST中，一个“数据组件”被称为“Model”，Model的定义采用了链式调用的方式，并且能重复定义props、views、actions等，MST会在内部将多次的定义进行合并处理，成为一个新的Model。</p>
<p>再来看上面的实现代码，代码中定义了三个BaseModel（提供基础功能的Model），Notification、Loadable以及RemoteResource。其中Notification提供消息通知的功能，Loadable提供了loading状态以及切换loading状态的方法，而RemoteResource在前两者的基础上，提供了加载远程资源的能力。</p>
<p>三个BaseModel的实现非常简单，并且与业务逻辑零耦合。最后，通过组合BaseModel并扩展出对应的功能，实现了ProductList与Favorites两个Model。</p>
<p>在构造应用的时候，把应用的功能拆分成这样一个个简单的BaseModel，这样应用的代码看起来就会赏心悦目并且更易于维护。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/mobx-state-tree/" rel="tag"># mobx-state-tree</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/10/03/javascript-观察者模式/" rel="next" title="JavaScript 观察者模式">
                <i class="fa fa-chevron-left"></i> JavaScript 观察者模式
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/10/07/MobX-State-Tree数据组件化开发-1-：MST基础/" rel="prev" title="[MobX State Tree数据组件化开发][1]：MST基础">
                [MobX State Tree数据组件化开发][1]：MST基础 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Table of Contents
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Overview
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">lhweb</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">39</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">categories</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">25</span>
                  <span class="site-state-item-name">tags</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#组件化的时代"><span class="nav-number">1.</span> <span class="nav-text">组件化的时代</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Flux模式"><span class="nav-number">2.</span> <span class="nav-text">Flux模式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MobX-State-Tree：数据组件化"><span class="nav-number">3.</span> <span class="nav-text">MobX State Tree：数据组件化</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">lhweb</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
